'use client'

import { useState, useEffect } from 'react'
import { useParams, useRouter } from 'next/navigation'
import { VmsCourseSection } from '@/types/Model'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { ArrowLeft, Save } from 'lucide-react'
import { toast } from '@/hooks/use-toast'
import AdvancedEditor from '@/components/tailwind/advanced-editor'
import { novelcopy } from '@/lib/copyContent'

export default function SectionEditPage() {
  const params = useParams()
  const router = useRouter()
  const courseId = params.id as string
  const sectionId = params.sectionId as string
  
  const [section, setSection] = useState<VmsCourseSection | null>(null)
  const [title, setTitle] = useState('')
  const [content, setContent] = useState('')
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)

  // 获取课程节详情
  const fetchSection = async () => {
    try {
      const token = localStorage.getItem('token')
      const response = await fetch(`/api/course/${courseId}/sections/${sectionId}`, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })
      
      if (!response.ok) {
        throw new Error('Failed to fetch section')
      }
      
      const sectionData = await response.json()
      setSection(sectionData)
      setTitle(sectionData.title)
      setContent(sectionData.content || '')
    } catch (error) {
      console.error('Error fetching section:', error)
      toast({
        title: '加载失败',
        description: '无法加载课程节内容',
        variant: 'destructive'
      })
    } finally {
      setLoading(false)
    }
  }

  // 保存课程节内容的函数，供 AdvancedEditor 调用
  const saveSectionContent = async (updatedCopy: any) => {
    try {
      const token = localStorage.getItem('token')
      const response = await fetch(`/api/course/${courseId}/sections/${sectionId}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
          title: updatedCopy.title || title,
          content: updatedCopy.content || content,
          content_md: updatedCopy.rich_content,
          published: updatedCopy.published,
          
        })
      })

      if (!response.ok) {
        throw new Error('Failed to save section content')
      }

      // 更新本地状态
      setContent(updatedCopy.content || updatedCopy.rich_content || content)
      if (updatedCopy.title) {
        setTitle(updatedCopy.title)
      }

      toast({
        title: '保存成功',
        description: '课程节内容已更新'
      })
    } catch (error) {
      console.error('Error saving section content:', error)
      toast({
        title: '保存失败',
        description: '请稍后重试',
        variant: 'destructive'
      })
      throw error // 重新抛出错误，让 AdvancedEditor 知道保存失败
    }
  }

  // 保存课程节
  const handleSave = async () => {
    if (!title.trim()) {
      toast({
        title: '标题不能为空',
        variant: 'destructive'
      })
      return
    }

    setSaving(true)
    try {
      const token = localStorage.getItem('token')
      const response = await fetch(`/api/course/${courseId}/sections/${sectionId}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
          title: title.trim(),
          content: content,
        })
      })

      if (!response.ok) {
        throw new Error('Failed to save section')
      }

      toast({
        title: '保存成功',
        description: '课程节已更新'
      })
      
      // 返回到课程详情页
      router.push(`/courses/${courseId}`)
    } catch (error) {
      console.error('Error saving section:', error)
      toast({
        title: '保存失败',
        description: '请稍后重试',
        variant: 'destructive'
      })
    } finally {
      setSaving(false)
    }
  }

  useEffect(() => {
    fetchSection()
  }, [courseId, sectionId])

  if (loading) {
    return (
      <div className="container mx-auto px-4 py-8">
        <div className="flex items-center justify-center h-64">
          <div className="text-lg">加载中...</div>
        </div>
      </div>
    )
  }

  if (!section) {
    return (
      <div className="container mx-auto px-4 py-8">
        <div className="flex items-center justify-center h-64">
          <div className="text-lg text-red-600">课程节不存在</div>
        </div>
      </div>
    )
  }

  // 处理内容格式，确保编辑器能正确显示
  const getEditorContent = () => {
    if (!content) {
      // 如果没有内容，返回默认的空内容结构的JSON字符串
      return JSON.stringify(novelcopy())
    }
    
    try {
      // 尝试解析现有内容
      JSON.parse(content)
      return content
    } catch {
      // 如果不是有效的JSON，返回默认内容的JSON字符串
      return JSON.stringify(novelcopy())
    }
  }

  // 创建一个适配 AdvancedEditor 的 copy 对象
  const editorCopy = {
    id: sectionId,
    title: title,
    content: getEditorContent(),
    rich_content: content,
    intro: ''
  }

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="max-w-4xl mx-auto">
        {/* Header */}
        <div className="flex items-center justify-between mb-6">
          <div className="flex items-center gap-4">
            <Button
              variant="ghost"
              size="sm"
              onClick={() => router.push(`/courses/${courseId}`)}
            >
              <ArrowLeft className="h-4 w-4 mr-2" />
              返回课程
            </Button>
            <h1 className="text-2xl font-bold">编辑课程节</h1>
          </div>
          {/* <Button
            onClick={handleSave}
            disabled={saving}
            className="flex items-center gap-2"
          >
            <Save className="h-4 w-4" />
            {saving ? '保存中...' : '保存'}
          </Button> */}
        </div>

        {/* Form */}
        <div className="space-y-6">
          {/* Title */}
          <div>
            <label className="block text-sm font-medium mb-2">
              标题
            </label>
            <Input
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              placeholder="请输入课程节标题"
              className="w-full"
            />
          </div>

          {/* Content Editor */}
          <div>
            <label className="block text-sm font-medium mb-2">
              内容
            </label>
            <div className="">
                <AdvancedEditor 
                    copy={editorCopy}
                    saveCopy={saveSectionContent}
                    showExportMD={true}
                    showScriptMaking={false}
                    showPPTMaking={false}
                    showSave={true}
                    showShare={false}
                />
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}